<template>
  <div class="bilibili-container">
    <!-- 顶部状态卡片 -->
    <el-row :gutter="20" class="status-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="status-card">
          <div class="card-content">
            <div class="icon-wrapper pink">
              <i class="el-icon-video-camera"></i>
            </div>
            <div class="info">
              <div class="label">总任务数</div>
              <div class="value">{{ total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="status-card">
          <div class="card-content">
            <div class="icon-wrapper blue">
              <i class="el-icon-video-play"></i>
            </div>
            <div class="info">
              <div class="label">运行中</div>
              <div class="value">{{ runningTasks }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
    </el-row>

    <!-- 服务器信息卡片 -->
    <el-card class="server-info" shadow="hover">
      <div class="server-header">
        <div class="server-title">
          <i class="el-icon-s-platform"></i>
          <span>服务器信息</span>
        </div>
        <el-tag type="success">运行中</el-tag>
      </div>
      <div class="server-content">
        <div class="info-item">
          <span class="label">服务器SID：</span>
          <span class="value">{{ $route.query.sid }}</span>
        </div>
        <div class="info-item">
          <span class="label">Server Key：</span>
          <el-tag size="medium" type="info">{{ $route.query.serverKey }}</el-tag>
        </div>
      </div>
    </el-card>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button-group>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
          新增任务
        </el-button>
        <el-button type="success" icon="el-icon-video-play" @click="handleBatchStart">
          批量启用
        </el-button>
        <el-button type="warning" icon="el-icon-video-pause" @click="handleBatchPause">
          批量停用
        </el-button>
      </el-button-group>
      
      <div class="search-box">
        <el-input
          v-model="queryParams.keyword"
          placeholder="搜索任务..."
          prefix-icon="el-icon-search"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleQuery"></el-button>
        </el-input>
      </div>
    </div>

    <!-- 任务列表 -->
    <el-card class="task-list" shadow="hover">
      <el-table
        v-loading="loading"
        :data="taskList"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务ID" prop="id" width="80" align="center" />
        <el-table-column label="视频标题" prop="videoTitle" min-width="200">
          <template slot-scope="scope">
            <div class="video-info">
              <el-tooltip :content="scope.row.videoTitle" placement="top">
                <span class="video-title text-ellipsis">{{ scope.row.videoTitle }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="视频链接" prop="videoUrl" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" :href="scope.row.videoUrl" target="_blank">
              {{ scope.row.videoUrl }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="BV号" prop="videoBv" width="140" align="center" />
        <el-table-column label="投币数" prop="currentCoins" width="80" align="center" />
        <el-table-column label="点赞数" prop="currentLikes" width="80" align="center" />
        <el-table-column label="收藏数" prop="currentFavorites" width="80" align="center" />
        <el-table-column label="三连执行命令" align="center" width="140">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              plain
              icon="el-icon-s-tools"
              @click="handleConfigCommand(scope.row)"
            >配置命令集</el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="isEnabled" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isEnabled === '1' ? 'success' : 'info'">
              {{ scope.row.isEnabled === '1' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createName" width="120" align="center" />
        <el-table-column label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              :icon="scope.row.isEnabled === '1' ? 'el-icon-video-pause' : 'el-icon-video-play'"
              @click="handleToggleStatus(scope.row)"
            >{{ scope.row.isEnabled === '1' ? '停用' : '启用' }}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              class="delete-btn"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加/修改对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="500px" 
      append-to-body
      :close-on-click-modal="false"
      class="custom-dialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="视频链接" prop="videoUrl">
          <el-input v-model="form.videoUrl" placeholder="请输入视频链接" />
        </el-form-item>
        <el-form-item label="视频BV号" prop="videoBv">
          <el-input v-model="form.videoBv" placeholder="请输入视频BV号" />
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-switch
            v-model="form.isEnabled"
            active-text="启用"
            inactive-text="停用"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <page-footer />
  </div>
</template>

<style lang="scss" scoped>
.bilibili-container {
  padding: 20px;
  height: 100%;
  position: relative;

  .status-cards {
    margin-bottom: 20px;

    .status-card {
      border-radius: 12px;
      transition: all 0.3s ease;
      border: none;
      overflow: hidden;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
      }

      .card-content {
        display: flex;
        align-items: center;
        padding: 20px;

        .icon-wrapper {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          i {
            font-size: 24px;
            color: #fff;
          }

          &.pink {
            background: linear-gradient(135deg, #ff6b81, #ff4757);
          }

          &.blue {
            background: linear-gradient(135deg, #70a1ff, #1e90ff);
          }

          &.purple {
            background: linear-gradient(135deg, #a8c0ff, #8e54e9);
          }

          &.orange {
            background: linear-gradient(135deg, #ffd371, #ff7f50);
          }
        }

        .info {
          .label {
            font-size: 14px;
            color: #8c8c8c;
            margin-bottom: 5px;
          }

          .value {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
          }
        }
      }
    }
  }

  .server-info {
    margin-bottom: 20px;
    border-radius: 12px;
    border: none;

    .server-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;

      .server-title {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;

        i {
          margin-right: 8px;
          color: #409EFF;
        }
      }
    }

    .server-content {
      padding-top: 15px;

      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .label {
          width: 100px;
          color: #606266;
        }

        .value {
          color: #303133;
          font-family: monospace;
        }
      }
    }
  }

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .search-box {
      width: 300px;
    }
  }

  .task-list {
    border-radius: 12px;
    border: none;

    .video-info {
      display: flex;
      align-items: center;

      .video-cover {
        width: 80px;
        height: 50px;
        border-radius: 4px;
        margin-right: 10px;
        object-fit: cover;
      }

      .video-title {
        display: inline-block;
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #303133;
        
        &:hover {
          color: #00a1d6;
        }
      }
    }

    .el-button {
      padding: 0 8px;

      &.delete-btn {
        color: #ff4757;
      }
    }
  }
}

// B站风格的自定义滚动条
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #99a9bf;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #f6f7f8;
}
</style>

<script>
import { 
  listBilibiliTask,
  getBilibiliTask,
  delBilibiliTask,
  addBilibiliTask,
  updateBilibiliTask
} from "@/api/system/task";
import PageFooter from '@/components/Footer'

export default {
  name: 'BilibiliTask',
  components: {
    PageFooter
  },
  data() {
    return {
      loading: false,
      total: 0,
      taskList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        serverSid: undefined,
        serverKey: undefined
      },
      selectedTasks: [],
      title: "",
      open: false,
      form: {},
      refreshTimer: null,
      rules: {
        videoBv: [
          { required: true, message: "视频BV号不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "视频链接不能为空", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    runningTasks() {
      return this.taskList.filter(task => task.status === 1).length
    },
    completedTasks() {
      return this.taskList.filter(task => task.status === 2).length
    },
    errorTasks() {
      return this.taskList.filter(task => task.status === 3).length
    }
  },
  created() {
    this.queryParams.serverSid = this.$route.query.sid;
    this.queryParams.serverKey = this.$route.query.serverKey;
    this.getList();
    this.startAutoRefresh();
  },
  beforeDestroy() {
    this.stopAutoRefresh();
  },
  methods: {
    getStatusType(status) {
      const types = {
        0: 'info',    // 未开始
        1: 'success'  // 运行中
      }
      return types[status ? 1 : 0] || 'info'
    },
    getStatusText(status) {
      const texts = {
        0: '未开始',
        1: '运行中'
      }
      return texts[status ? 1 : 0] || '未知'
    },
    handleSelectionChange(selection) {
      this.selectedTasks = selection
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.loading = true;
      this.getList();
    },
    getList() {
      if (this.taskList.length === 0) {
        this.loading = true;
      }
      listBilibiliTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        if (this.loading) {
          this.loading = false;
        }
      }).catch(() => {
        if (this.loading) {
          this.loading = false;
        }
      });
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加B站任务";
      this.form.serverSid = this.$route.query.sid;
      this.form.serverKey = this.$route.query.serverKey;
      this.form.isEnabled = 0;
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBilibiliTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改B站任务";
      });
    },
    handleDelete(row) {
      const taskId = row.id || this.ids;
      this.$modal.confirm('是否确认删除任务编号为"' + taskId + '"的数据项？').then(function() {
        return delBilibiliTask(taskId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleBatchStart() {
      if (this.selectedTasks.length === 0) {
        this.$message.warning("请选择要启用的任务");
        return;
      }
      // TODO: 实现批量启用逻辑
    },
    handleBatchPause() {
      if (this.selectedTasks.length === 0) {
        this.$message.warning("请选择要停用的任务");
        return;
      }
      // TODO: 实现批量停用逻辑
    },
    handleToggleStatus(row) {
      const text = row.isEnabled === '1' ? '停用' : '启用';
      this.$modal.confirm('确认要' + text + '"' + row.id + '"任务吗？').then(function() {
        return updateBilibiliTask({
          ...row,
          isEnabled: row.isEnabled === '1' ? '0' : '1'
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(text + "成功");
      }).catch(() => {});
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        videoUrl: undefined,
        videoBv: undefined,
        isEnabled: '0',
        serverSid: undefined,
        serverKey: undefined
      };
      this.resetForm("form");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getList();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBilibiliTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBilibiliTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 配置命令集按钮操作 */
    handleConfigCommand(row) {
      this.$router.push({
        path: '/server/command',
        query: {
          videoId: row.id,
          videoBv: row.videoBv
        }
      });
    },
    startAutoRefresh() {
      this.refreshTimer = setInterval(() => {
        if (this.loading || this.open) {
          return;
        }
        this.getList();
      }, 2000);
    },
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
  }
}
</script>
